package cn.jdy.plugins.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cn.jdy.authority.entity.Organ;
import cn.jdy.authority.entity.User;
import cn.jdy.authority.entity.UserRole;
import cn.jdy.authority.service.OrganService;
import cn.jdy.authority.service.UserRoleService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.plugins.entity.Line;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.entity.RelatedVideo;
import cn.jdy.plugins.service.LineService;
import cn.jdy.plugins.service.LiveService;
import cn.jdy.plugins.service.RelatedVideoService;
/***
 * @desc 相关视频控制类
 * @author lph
 * 
 */
@Controller
@RequestMapping("/relatedVideo")
public class RelatedVideoCtrl extends BaseCtrl {
	@Autowired
	private RelatedVideoService relatedVideoService;
	@Autowired
	private LiveService liveService;
	@Autowired
	protected HttpSession session;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private LineService lineService;
	@Autowired
	private OrganService organService;
	// 默认列表路径
	private static String viewName = "redirect:/relatedVideo/list?s=";

	/**
	 * 初始化
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(required = false) Integer s,String mainid, String liveid) {
		ModelAndView mv = new ModelAndView();
		if (s != null)
			switch (s) {
			case 1:
				mv.addObject("msg", "保存成功！");
				break;
			case 2:
				mv.addObject("msg", "更新成功！");
				break;
			case 3:
				mv.addObject("msg", "删除成功！");
				break;
			case 4:
				mv.addObject("msg", "操作失败！");
				break;
			default:
				break;
			}
		
		mv.addObject("mainid", mainid);
		long id=Long.parseLong(liveid);
		mv.addObject("liveids", liveService.findOne("id",id).getCurrentStatus());
		mv.addObject("liveid", liveid);
		mv.setViewName("/operate/relatedvideoList.jsp");
		return mv;
	}
	
	
	/**
	 * 异步查询
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(Live Live,String mainid,String startTime, String endTime) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Long iTotalDisplayRecords = 0L;
		Long iTotalRecords =0L;
		try {
			List<Live> dataList = new ArrayList<Live>();
			//如果线路不为空的话就根据当前先线路去查
			if (!StringUtil.isNullOrEmpty(mainid)) {
				dataList = liveService.query(Live, startTime,endTime);
				iTotalDisplayRecords = liveService.count(Live,startTime,endTime);
				iTotalRecords = liveService.count(Live);
			} else {
				//如果为空的话当前用户是系统管理员或超级管理员的话查所有直播
				User user = (User) session.getAttribute("user");
				List<UserRole> list = userRoleService.find("userid", user.getId());
				String roleid = "";
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).getRoleid().equals("4028b3044de1a396014de1ba2b2e0000")|| list.get(i).getRoleid().equals("ff8080814db89f0a014db8d169290000")) {
					    roleid = "0";
					}
				}
				if(roleid=="0"){
					dataList = liveService.query(Live,startTime,endTime);
					iTotalDisplayRecords = liveService.count(Live,startTime,endTime);
					iTotalRecords = liveService.count(Live);
				}else{
					//如果为直播管理员则查询该用户的所拥有线路下的所有直播
					List<Line> lineList = new ArrayList<Line>();	
					if (user != null) {
						Organ organ = organService.findOne("id", user.getOrganid()); // 当前用户所在的机构
						if (organ != null) {
							lineList = lineService.find("organid", organ.getId()); // 通过机构id查询所有线路
							String lineId = "";
							for (int i = 0; i < lineList.size(); i++) {
								lineId = lineId + lineList.get(i).getId() + ",";
							}
							if(""!= lineId){
								dataList = liveService.queryRelatedlive(lineId,Live.getName(),startTime,endTime,Live.getiDisplayLength(),Live.getiDisplayStart());
							}
							iTotalDisplayRecords = (long) dataList.size();
							iTotalRecords = (long) dataList.size();
						}	
					}
				}	
			}
			jsonMap.put("dataList", dataList);
			jsonMap.put("iTotalDisplayRecords",iTotalDisplayRecords);
			jsonMap.put("iTotalRecords",iTotalRecords);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "出现异常。。。。。在方法：queryByPage 中", e);
		}
		return jsonMap;
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	// 该方法已停止使用--不允许用户进行编辑
	/*
	 * @RequestMapping("/edit/{id}") public ModelAndView edit(@PathVariable Long
	 * id,String username) { ModelAndView mv = new
	 * ModelAndView("/operate/relatedvideoDetail.jsp"); User user = (User)
	 * session.getAttribute("user"); List<Live> datalist; if(username==null){
	 * datalist= liveService.find("username",user.getUsername()); }else{
	 * datalist= liveService.find("username",username); }
	 * mv.addObject("datalists", datalist); mv.addObject("data", id==null||id==0
	 * ? id : this.relatedVideoService.find(id)); return mv; }
	 */


	/**
	 * 保存（更新） 
	 * @param 相关视频
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(RelatedVideo relatedVideo, String videoId,String liveid) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		//获取域名
		StringBuffer urls = request.getRequestURL();
		String str = urls.toString().split(":")[1];
		String Url = str.substring(2, str.length());
		//String Url = urls.delete(urls.length() - request.getRequestURI().length(), urls.length()).toString();
		try {
			if (relatedVideo.getId() == null) {
					String[] ids = videoId.split(",");
					for (int i = 0; i < ids.length; i++) {
						String videoid = ids[i].toString();
						long id = Long.parseLong(videoid);
							Live live=liveService.findOne("id",id);
							live.setZburl("http://"+Url + "/" + "w" + "/"+ "live" + "/" + "index" + "/" + live.getId());
							live.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
							liveService.update(live);
					}
					long id = Long.parseLong(liveid);
					Live live=liveService.findOne("id",id);
					live.setCurrentStatus(videoId);
//					for (int i = 0; i < lid.length; i++) {
//						String noid = lid[i].toString();
//						System.out.println("noid"+noid);
////						long id = Long.parseLong(noid);
////							Live live=liveService.findOne("id",id);
////							live.setCurrentStatus("0");
////							//live.setZburl("http://"+Url + "/" + "w" + "/"+ "live" + "/" + "index" + "/" + live.getId());
							live.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
							liveService.update(live);
//					}
					jsonMap.put("ok", "保存成功");
			}
		} catch (Exception e) {

		}
		return jsonMap;
	}
	
	/**
	 * 删除视频
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping("/del")
	public ModelAndView del(String videoId) {
		ModelAndView mv = new ModelAndView();
		try {
			if (videoId != null) {
				String[] ids = videoId.split(";");
				for (int i = 0; i < ids.length; i++) {
					String videoid = ids[i].toString();
					long id = Long.parseLong(videoid);
					RelatedVideo related = relatedVideoService.findOne("id", id);
					if (related != null) {
						this.relatedVideoService.delete(related.getId());
						mv.setViewName(this.viewName.concat("3"));
					}
				}
			}

		} catch (Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return mv;
	}

	/**
	 * 点击次数
	 * @param
	 * @return
	 */
	 /*@RequestMapping("/updateNumber")
	 @ResponseBody
	 public Map<String, Object> updateNumber(Long id) {
		 Map<String, Object> jsonMap = new HashMap<String, Object>();
	 try {
		 RelatedVideo relatedVideo=relatedVideoService.find(id);
		 int nuber = 0;
		 if(relatedVideo!=null){
			 if(relatedVideo.getWatchNumber()==null){
				 nuber=0;
			 }else{
				 nuber=relatedVideo.getWatchNumber();
			 }
			 relatedVideo.setWatchNumber(nuber+1);
			 relatedVideo.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
			 relatedVideoService.update(relatedVideo);
		 }else{
			 
		 }
	 } catch(Exception e) {
	        BaseLog.e(this.getClass(), "修改异常", e);
	 }
	 return jsonMap;
	 }*/

	 /**
	  * @desc 获取视频信息
	  * @throws IOException
	  * @throws ParseException
	  */
	  /*@SuppressWarnings("unchecked") 
	  @RequestMapping("/getVideo") 
	  @ResponseBody 
	  public Map getVideo(@RequestParam("liveId") Long liveId)throws IOException, ParseException { 
		  //User user = (User)session.getAttribute("user"); 
		  Live live=liveService.findOne("id",liveId);
		  String app = ""; 
		  String livename = ""; 
		  Long id = null;
	  
		  if(live!=null){ 
			  id=live.getId(); 
			  livename=live.getName(); 
			  String mainurl=live.getMainurl(); app=mainurl.split("com/")[1].split("/")[0];
			  System.out.println(app); 
		  }
		  JsonUtil json =new JsonUtil(); 
		  Map<Object, Object> map = new HashMap<Object, Object>(); 
		  String videoTime=relatedVideoService.queryUptime(); 
		  long v=0; 
		  if(null !=videoTime && "" != videoTime && "null"!= videoTime &&!("").equals(videoTime)){ 
			  String re_time = null; 
			  SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
			  Date d = sdf.parse(videoTime); 
			  long l = d.getTime(); 
			  String str = String.valueOf(l); 
			  re_time = str.substring(0, 10); 
			  v = Long.valueOf(re_time).longValue(); 
		  } 
		  long a[]={v+1,2109385380};
		  map.put("access_id", "572175713955"); map.put("access_key","5JD4jHd7iwQP8SlFpy2MTP9p3J31e7U8"); 
		  map.put("app",app);
		  //此参数用来区分来自那条线路下的视频 
		  map.put("uptime",a); 
		  json.toJson(map); String tickets=HttpUtil.sendPost("http://openapi.aodianyun.com/v2/VOD.GetVodList",json.toJson(map),"UTF-8", 0); 
		  HashMap<String, Object> map2=(HashMap<String,Object>) JsonUtil.toObj(tickets, Map.class); 
		  String Flag=map2.get("Flag").toString(); 
		  if(Flag.equals("100")){ 
			  Map lists =null; 
			  List<Map> list=(List) map2.get("List"); 
			  for(int i=0;i<list.size();i++){ 
				  lists=list.get(i);
		          //将时间戳转换成时间 
				  String startTime; 
				  //开始时间 
				  String endTime; 
				  //结束时间
				  String uptime; 
				  //发布时间 
				  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
				  long start = Long.valueOf(lists.get("start").toString()); 
				  startTime = sdf.format(new Date(start * 1000L));
		  
				  long end = Long.valueOf(lists.get("end").toString()); endTime =
				  sdf.format(new Date(end * 1000L));
		  
		          long uptimes = Long.valueOf(lists.get("uptime").toString()); 
		          uptime =sdf.format(new Date(uptimes * 1000L)); 
		          //创建对象并保存 
		          RelatedVideo relatedVideo=new RelatedVideo();
				  relatedVideo.setVideoUrl(lists.get("url").toString()); //播放地址
				  relatedVideo.setVideoName((lists.get("title").toString())); //视频名称
				  relatedVideo.setStartTime(startTime); //开始时间
				  relatedVideo.setEndTime(endTime); //结束时间
				  relatedVideo.setVideoLength(lists.get("duration").toString());//视频时长
				  relatedVideo.setVideoImage(lists.get("thumbnail").toString());//视频封面
				  relatedVideo.setReleaseTime(uptime); //发布时间
				  relatedVideo.setVideoDesc(lists.get("desc").toString()); //视频描述
				  relatedVideo.setWatchNumber(0); //观看人数初始为0 relatedVideo.setLiveId(id);
				  relatedVideo.setLiveName(livename);
				  relatedVideoService.save(relatedVideo); map.put("ok", "数据已更新");
				  System.out.println(relatedVideo);
		  
		  } 
		  }else if(Flag.equals("1006")){ 
			  map.put("no", "账号认证失败"); 
		  }else{
			  map.put("sy", "暂无新的数据"); 
		  }
	      return map; 
	  }*/
	 
}
